
package com.base.common;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.util.Date;

import org.springframework.util.StringUtils;

import com.base.util.JUtil;

public class DateEditor extends PropertyEditorSupport{
	
	private String farMatString = "yyyy-MM-dd";
	
	private boolean allowEmpty = true;  
	
	public DateEditor() {  
	}  
	
	@Override  
	public void setAsText(String text) throws IllegalArgumentException {  
		if (this.allowEmpty && !StringUtils.hasText(text)) {  
			setValue(null);  
		} else {  
			try {  
				if(text.contains(":")){
					String farMatString = "yyyy-MM-dd HH:mm:ss";
					setValue(JUtil.getDate(text,farMatString ));  
					return;
				}
				setValue(JUtil.getDate(text, farMatString));  
			} catch (ParseException ex) {  
				throw new IllegalArgumentException("Could not parse date: " + ex.getMessage(), ex);  
			}  
		}  
	}  
	
	
	@Override  
	public String getAsText()  {  
		Date value = (Date) getValue();  
		if(null == value){
			return "";
		}
		try {
			return JUtil.getDateStr(value, farMatString);
		} catch (ParseException e) {
			e.printStackTrace();
			return "";
		}
	}  
}